<template>
  <el-upload class="hui-uploader" :accept="accept" :action="action" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
    <h-image v-if="src" :src="src" :width="width || size" :height="height || size" mode="background-image"></h-image>
    <!-- <i v-else class="el-icon-plus hui-uploader-icon"></i> -->
    <h-icon v-else icon="icon-plus" :length="width || size" size="48px" mode="dark"></h-icon>
  </el-upload>
</template>

<script>
export default {
  name: 'hpro-upload-img',
  componentName: 'hpro-upload-img',
  data () {
    return {
      action: 'https://jsonplaceholder.typicode.com/photos/',
      accept: 'image/jpeg, image/jpg, image/png, image/gif'
    }
  },
  model: {
    prop: 'src',
    event: 'change'
  },
  props: {
    src: [Array, String],
    multiple: Boolean,
    width: String,
    height: String,
    size: {
      type: String,
      default: '158px'
    }
  },
  computed: {
    _src: {
      get () {
        if (this.multiple) {
          return this.value
        } else {
          let tmp = []
          tmp.push(this.value)
          return tmp
        }
      },
      set (val) {
        if (this.multiple) {
          this.$emit('update:src', val)
          this.$emit('change', val)
        } else {
          this.$emit('update:src', val[0])
          this.$emit('change', val[0])
        }
      }
    }
  },
  methods: {
    handleAvatarSuccess (res, file) {
      this._src = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isImage = file.type === 'image/jpeg' || 'image/jpg' || 'image/png' || 'image/gif'
      const isLimit500K = file.size / 1024 < 500
      if (!isImage) {
        this.$message.error('上传头像图片只能是 jpg / jpeg / png / gif 格式!')
      }
      if (!isLimit500K) {
        this.$message.error('上传头像图片大小不能超过 500K!')
      }
      return isImage && isLimit500K
    }
  }
}
</script>

<style lang="less">
@import '../../common/h-theme/_variable.less';

.hui-uploader {
  .el-upload {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border: 1px dashed @--border-color-base;
    border-radius: 4px;
    // background-color: @--background-color-base;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    &:hover {
      border-color: @--color-primary;
    }

    &:active, &:focus {
      color: unset;
    }
  }

  .hui-uploader-icon {
    font-size: 32px;
  }
}
</style>
